<template>
  <div class="container dark-theme">
    <!-- 头部导航栏 -->
    <div class="header">
      <div class="logo">“沈誉通”信用生活综合系统</div>
      <div class="nav">
        <!-- <router-link to="/home">首页</router-link> -->
        <router-link to="/credit-life">信用生活</router-link>
        <router-link to="/credit-business">信用商业</router-link>
        <router-link to="/behavior">亲社会行为</router-link>
        <router-link to="/news">新闻资讯</router-link>
        <router-link to="/credit-management">信用管理</router-link>
      </div>
      <div class="user-menu" ref="userMenu">
        <div class="notification">
          <router-link to="/notice">
            <i class="el-icon-message"></i>
          </router-link>
        </div>
        <div class="avatar-box">
          <img :src="user.icon" class="avatar" alt="用户头像" @click.stop="toggleMenu" />
        </div>
        <div v-if="isMenuOpen" class="dropdown-menu">
          <div class="menu-item" @click="goToProfile">个人信息</div>
          <div class="menu-item" @click="logout">退出登录</div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 上部分：商品轮播图 -->
      <div class="section carousel-section">
        <div class="section-header">
          <h2 class="section-title">精选商品</h2>
          <el-button type="primary" @click="goToAllProducts">全部商品</el-button>
        </div>
        <el-carousel :interval="4000" type="card" height="400px">
          <el-carousel-item v-for="(item, index) in products" :key="index" @click.native="goToProduct(item.id)">
            <div class="carousel-content">
              <img :src="item.images" :alt="item.title">
              <div class="carousel-info">
                <h3>{{ item.title }}</h3>
                <p class="price">¥{{ (item.currentPrice / 100).toFixed(2) }}</p>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>

      <!-- 分隔线 -->
      <div class="divider"></div>

      <!-- 中间部分：房屋租赁 -->
      <div class="section houses-section">
        <div class="section-header">
          <h2 class="section-title">精选出租屋</h2>
          <el-button type="primary" @click="goToAllHouses">全部出租屋</el-button>
        </div>
        <el-carousel :interval="4000" type="card" height="400px">
          <el-carousel-item v-for="item in houses" :key="item.id" @click.native="goToHouse(item.id)">
            <div class="carousel-content">
              <img :src="item.images" :alt="item.title">
              <div class="carousel-info">
                <h3>{{ item.title }}</h3>
                <p class="price">¥{{ (item.currentPrice / 100).toFixed(2) }}</p>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>

      <!-- 分隔线 -->
      <div class="divider"></div>

      <!-- 下部分：酒店预订 -->
      <div class="section rooms-section">
        <div class="section-header">
          <h2 class="section-title">精选酒店房间</h2>
          <el-button type="primary" @click="goToAllRooms">全部酒店房间</el-button>
        </div>
        <el-carousel :interval="4000" type="card" height="400px">
          <el-carousel-item v-for="item in rooms" :key="item.id" @click.native="goToRoom(item.id)">
            <div class="carousel-content">
              <img :src="item.images" :alt="item.title">
              <div class="carousel-info">
                <h3>{{ item.title }}</h3>
                <p class="price">¥{{ (item.currentPrice / 100).toFixed(2) }}</p>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'CreditBusiness',
  data() {
    return {
      user: {},
      isMenuOpen: false,
      products: [],
      houses: [],
      rooms: [],
    };
  },
  created() {
    this.queryUser();
    this.fetchRooms();
    this.fetchProducts();
    this.fetchHouses();

  },
  methods: {

    async fetchProducts() {
      try {
        const response = await axios.get('/commodity/good/list/pageGood', {
          params: {
            page: 1,
            pageSize: 3
          }
        });
        if (response.data.success) {
          this.products = response.data.data.products
        } else {
          this.$message.error(response.data.errorMsg || '获取商品列表失败');
        }
      } catch (error) {
        this.$message.error('网络错误，请稍后重试');
      }
    },


    async fetchHouses() {
      try {
        const response = await axios.get('/commodity/house/list/pageHouse', {
          params: {
            page: 1,
            pageSize: 6
          }
        });
        if (response.data.success) {
          this.houses = response.data.data.houses
        } else {
          this.$message.error(response.data.errorMsg || '获取出租屋列表失败');
        }
      } catch (error) {
        this.$message.error('网络错误，请稍后重试');
      }
    },


    async fetchRooms() {
      try {
        const response = await axios.get('/commodity/room/list/pageRoom', {
          params: {
            page: 1,
            pageSize: 6
          }
        });
        if (response.data.success) {
          this.rooms = response.data.data.rooms
        } else {
          this.$message.error(response.data.errorMsg || '获取出租屋列表失败');
        }
      } catch (error) {
        this.$message.error('网络错误，请稍后重试');
      }
    },


    toggleMenu() {
      this.isMenuOpen = !this.isMenuOpen;
    },
    closeMenuOnClickOutside(event) {
      const menu = this.$refs.userMenu;
      if (menu && !menu.contains(event.target)) {
        this.isMenuOpen = false;
      }
    },
    goToProfile() {
      this.$router.push('/user-information');
      this.isMenuOpen = false;
    },
    logout() {
      axios.post('/users/user/logout')
        .then(() => {
          sessionStorage.removeItem('token');
          this.$router.push('/');
        })
        .catch(err => this.$message.error(err.message));
    },
    queryUser() {
      axios.get('/users/user/me', {
        headers: { Authorization: `${localStorage.getItem('token')}` }
      }).then(({ data }) => {
        if (data.success && data.data) {
          this.user = data.data;
          if (this.user.icon && !this.user.icon.startsWith('http')) {
            this.user.icon = `${this.user.icon}`;
          }
          this.queryUserInfo();
        }
      });
    },
    queryUserInfo() {
      axios.get(`/users/user/basic`)
        .then(({ data }) => {
          this.info = data || { introduce: '' };
          sessionStorage.setItem('userInfo', JSON.stringify(data));
        })
        .catch(err => this.$message.error(err.message));
    },
    goToProduct(id) {
      const token = localStorage.getItem('token');
      const userId = this.user.id;
      axios
        .post(
          `/commodity/good/click?goodId=${id}&userId=${userId}`,
          {},
          {
            headers: { Authorization: `Bearer ${token}` },
          }
        )
        .then(({ data }) => {
          if (!data.success) {
            this.$message.error(data.errorMsg || '记录点击失败');
          } else {
            console.log(`商品 ${id} 点击记录成功`);
          }
          this.$router.push(`/credit-business/product-detail/${id}`);
        })
        .catch((error) => {
          this.$message.error('记录点击失败：' + (error.response?.data?.errorMsg || error.message));
          console.error('点击记录失败:', error);
          this.$router.push(`/credit-business/product-detail/${id}`);
        });
    },
    goToAllProducts() {
      this.$router.push('/credit-business/products');
    },
    goToRoom(id) {
      this.$router.push(`/credit-business/room-detail/${id}`);
    },
    goToAllRooms() {
      this.$router.push('/credit-business/rooms');
    },
    goToHouse(id) {
      this.$router.push(`/credit-business/house-detail/${id}`);
    },
    goToAllHouses() {
      this.$router.push('/credit-business/houses');
    }
  }
};
</script>

<style scoped>
.container.dark-theme {
  background: radial-gradient(ellipse at center, #001e3c 0%, #000 100%);
  min-height: 100vh;
  color: #fff;
  font-family: 'Microsoft YaHei', sans-serif;
}

.header {
  display: flex;
  justify-content: space-between;
  padding: 10px 30px;
  background: #002d52;
  align-items: center;
}

.logo {
  font-size: 20px;
  color: #4fc3f7;
}

.nav a {
  margin: 0 10px;
  color: #fff;
  text-decoration: none;
}

.user-menu {
  position: relative;
  display: flex;
  align-items: center;
}

.notification {
  margin-right: 10px;
}

.notification a {
  color: #fff;
  text-decoration: none;
}

.notification i {
  font-size: 24px;
  color: #4fc3f7;
}

.notification i:hover {
  color: #2196f3;
}

.avatar-box img.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  cursor: pointer;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background: #002d52;
  border-radius: 4px;
  padding: 5px 0;
  min-width: 120px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.menu-item {
  padding: 8px 16px;
  cursor: pointer;
  color: #fff;
}

.menu-item:hover {
  background: #014b75;
}

.main-content {
  padding: 20px;
}

.section {
  margin-bottom: 40px;
}

.section-title {
  color: #4fc3f7;
  margin-bottom: 20px;
  font-size: 24px;
}

.carousel-section {
  margin-bottom: 40px;
}

.carousel-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 45, 82, 0.8);
  border-radius: 8px;
  overflow: hidden;
}

.carousel-content img {
  width: 100%;
  height: 70%;
  object-fit: cover;
}

.carousel-info {
  padding: 15px;
  text-align: center;
}

.carousel-info h3 {
  margin: 0;
  color: #fff;
}

.price {
  color: #4fc3f7;
  font-size: 18px;
  margin: 5px 0;
}

.hotel-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.hotel-card {
  background: rgba(0, 45, 82, 0.8);
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s;
}

.hotel-card:hover {
  transform: translateY(-5px);
}

.hotel-image img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.hotel-info {
  padding: 15px;
}

.hotel-info h3 {
  margin: 0;
  color: #fff;
}

.location {
  color: #b0bec5;
  margin: 5px 0;
}

.rating {
  margin-top: 10px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header .el-button {
  background: #003b64;
  border: 1px solid #4fc3f7;
  color: #4fc3f7;
}

.section-header .el-button:hover {
  background: #4fc3f7;
  color: #fff;
}

.divider {
  height: 1px;
  background: linear-gradient(to right, transparent, #4fc3f7, transparent);
  margin: 40px 0;
}
</style>
